package com.filldream.fastboot.core.aop;

import com.filldream.fastboot.base.config.DbContextHolder;
import com.filldream.fastboot.common.annotation.DataSourceAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@Order(-100) //这是为了保证AOP在事务注解之前生效,Order的值越小,优先级越高
@Slf4j
public class DataSourceSwitchAop {

    //---------方法注解数据源---------
    /**定义一个切入点*/
    @Pointcut("@annotation(com.filldream.fastboot.common.annotation.DataSourceAnnotation)")
    public void autoAspect() {
    }

    @Before( "autoAspect()" )
    public void autoDataSource(JoinPoint pjp) {

        //获取注解
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();
        DataSourceAnnotation dataSource = targetMethod.getAnnotation(DataSourceAnnotation.class);
        String s = dataSource.dbName();

        log.info("切换到"+s+"数据源...");
        DbContextHolder.setDbType(s);
    }

}
